import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';
import {getUserInfo, getGrainInfo, getImTokenAdmin} from "@/services/login";
import { loadingService } from "@/utils/loadingServer"
import {getToken, clearStorage} from "@/utils";
import { useRouter } from "expo-router";
import {getOpenImSelfByToken} from "@/services/openImServices";
import {initSDK, platformID} from "@/utils/ImCommon";
import {useSelector} from "react-redux";
import {RootState} from "@/store";


type LoginState = {
    phone?: string,
    loginInfo: any,
    userInfo: any,
    tokenInfo: any,
    hasLogin: boolean,
    gainInfo: any
    locationInfo: any,
    imToken: string,
};

const initData = {
    phone: "",
    loginInfo: {},
    tokenInfo: {},
    userInfo: {},
    hasLogin: false,
    gainInfo: {},
    locationInfo: {
        province: "",
        city: "",
    },
    imToken: "",
};

const initialState: LoginState = {
    phone: "",
    loginInfo: {},
    tokenInfo: {},
    userInfo: {},
    hasLogin: false,
    gainInfo: {},
    locationInfo: {},
    imToken: "",
};

const LoginSlice = createSlice({
    name: 'login',
    initialState,
    reducers: {
        addPhone(state, action: any): void {
            state.phone = action.payload.phone;
        },
        setLoginInfo(state, action: any): void {
            state.loginInfo = action.payload.loginInfo;
        },
        setTokenInfo(state, action: any): void {
            state.token = action.payload.tokenInfo;
        },
        setUserInfo(state, action: any): void {
            state.userInfo = action.payload;
        },
        setHasLogin(state, action: any): void {
            console.log('setHasLogin', action)
            state.hasLogin = action.payload;
        },
        setGrainInfo(state, action: any): void {
            state.gainInfo = action.payload;
        },
        resetState(state, action: any) {
            console.log('state', state);
            state = {
                ...initData,
            }
        },
        setLocationInfo(state, action: any) {
            console.log('ac', action.payload)
            state.locationInfo = action.payload.locationInfo;
        },
        setImToken(state, action: any): void {
            console.log('出发setImTokensetImToken', action)
            state.imToken = action.payload;
        },
    },

});

export const { setLocationInfo, resetState, phone, addPhone, setLoginInfo, setTokenInfo, setHasLogin, setUserInfo, tokenInfo, setGrainInfo, imToken, setImToken  } = LoginSlice.actions;

// 定义一个异步函数，用于获取用户信息
export const getUserInfoDetail = () => {
    return async (dispatch, getState) => {
        // console.log('getToken', await getToken())
        const state = getState();

        getUserInfo()
            .then(res => {
                dispatch(setHasLogin(true))
                dispatch(setUserInfo(res.data))
                loadingService.hide();
                const userInfo = res.data;

                if (state?.login?.imToken) {
                    initSDK(userInfo?.uid, imToken);
                } else {
                    getImTokenAdmin()
                        .then(res => {
                            const adminToken = res?.data?.imAdminToken;
                            getOpenImSelfByToken(adminToken, userInfo?.uid, platformID)
                                .then(r => {
                                    dispatch(setImToken(r.data.token));
                                    initSDK(userInfo?.uid, r.data.token);
                                })
                                .catch(e => {
                                    console.log('e', e);
                                });
                        })
                        .catch(err => {
                            console.log('err', err);
                        })
                };

            })
            .catch(err => {
                console.log('err', err);
            })
    };
};

export const getGrainInfoDetail = () => {
    return async (dispatch) => {
        getGrainInfo()
            .then(res => {
                dispatch(setGrainInfo(res.data));
                console.log('res', res.data);
            })
            .catch(err => {
                console.log('err', err)
            })
    };

};

export const loginOut = () => {
    return async (dispatch) => {

        clearStorage();
        dispatch(setHasLogin(false));
        dispatch(setUserInfo({}))
        dispatch(addPhone(""))
        dispatch(setLoginInfo({}))
        dispatch(setTokenInfo({}))
        dispatch(setGrainInfo({}))
    };

};


export default LoginSlice.reducer;
